<template>
  <div class="vue-cropper">
    <div class="cropper-block">
      <vueCropper
        ref="cropper"
        :img="option.img"
        :outputSize="option.size"
        :outputType="option.outputType"
        :info="true"
        :full="option.full"
        :canMove="option.canMove"
        :canMoveBox="option.canMoveBox"
        :fixedBox="option.fixedBox"
        :original="option.original"
        :autoCrop="option.autoCrop"
        :autoCropWidth="option.autoCropWidth"
        :autoCropHeight="option.autoCropHeight"
        :centerBox="option.centerBox"
        :high="option.high"
        :infoTrue="option.infoTrue"
        @realTime="realTime"
        @cropMoving="cropMoving"
        :enlarge="option.enlarge"
        :mode="option.mode"
      ></vueCropper>
    </div>
    <div class="btn-block">
      <label class="handel-btn" for="uploads">选取图片</label>
      <input type="file" id="uploads" ref="referenceUpload" style="position:absolute; clip:rect(0 0 0 0);"
             accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event)">
      <el-button size="small" type="primary" @click="changeScale(1)"><i class="fa fa-plus"></i></el-button>
      <el-button size="small" type="primary" @click="changeScale(-1)"><i class="fa fa-minus"></i></el-button>
      <el-button size="small" type="primary" @click="rotateLeft"><i class="fa fa-rotate-left"></i></el-button>
      <el-button size="small" type="primary" @click="rotateRight"><i class="fa fa-repeat"></i></el-button>
      <el-button size="small" type="danger" @click="clearCrop">清 除</el-button>
      <el-button size="small" type="success" @click="finish" :loading="isLoading">上 传</el-button>
      <span style="color: red">(可上传jpg, png, gif格式，且不超过2M)</span>
    </div>
    <section class="pre-block">
      <!--<p>头像裁剪</p>-->
      <!--<div class="show-preview" :style="{'width': '150' + 'px', 'height': '150' + 'px',  'overflow': 'hidden',-->
      <!--'margin': '5px','border-radius':'50%'}">-->
      <!--<div :style="previews.div">-->
      <!--<img :src="previews.url" :style="previews.img">-->
      <!--</div>-->
      <!--</div>-->
      <p>裁剪预览：<span style="color: red">（默认为建议裁剪尺寸：{{option.autoCropWidth +' x '+ option.autoCropHeight}}）</span></p>
      <div :style="{'width': previews.w + 'px', 'height': previews.h + 'px',  'overflow': 'hidden',
							'margin': '5px'}">
        <div :style="previews.div">
          <img :src="previews.url" :style="previews.img">
        </div>
      </div>
    </section>
    <div class="upload-success" v-if="myUrl!==''">
      <p>已传图片：</p>
      <div :style="{'width':option.autoCropWidth+'px','height':option.autoCropHeight+'px'}">
        <img :src="$global.baseUrl+myUrl">
      </div>
    </div>
  </div>
</template>

<script>
  import {VueCropper} from 'vue-cropper'
  import Api from '@/constants/Api'

  export default {
    props: {
      value: {
        type: String,
        default: ''
      },
      cropWidth: {
        type: [Number, String]
      },
      cropHeight: {
        type: [Number, String]
      }
    },
    components: {
      VueCropper
    },
    data() {
      return {
        isLoading: false,
        myUrl: this.value,
        fileName: '',
        oldFile: {},
        previews: {},
        option: {
          img: '',
          size: 1,
          full: false,
          outputType: 'png',
          canMove: true,
          fixedBox: false,
          original: false,
          canMoveBox: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          autoCropWidth: this.cropWidth === '' ? 200 : this.cropWidth,
          autoCropHeight: this.cropHeight === '' ? 150 : this.cropHeight,
          centerBox: false,
          high: true,
          cropData: {},
          enlarge: 1,
          mode: 'contain'
        },
        previewStyle: {}
      }
    },
    watch: {
      value(newUrl) {
        this.myUrl = newUrl
      },
      myUrl(val) {
        this.$emit('input', val)
      },
      cropWidth(val) {
        let _cropWidth = val === '' ? 200 : val
        this.option.autoCropWidth = _cropWidth
      },
      cropHeight(val) {
        let _cropHeight = val === '' ? 150 : val
        this.option.autoCropHeight = _cropHeight
      }
    },
    methods: {
      changeScale(num) {
        num = num || 1
        this.$refs.cropper.changeScale(num)
      },
      rotateLeft() {
        this.$refs.cropper.rotateLeft()
      },
      rotateRight() {
        this.$refs.cropper.rotateRight()
      },
      finish() {
        const vm = this
        if (vm.fileName === '') {
          vm.$message.error('请选择图片')
          return false
        }
        vm.isLoading = true
        // 新增请求头
        let config = {
          headers: {'Content-Type': 'multipart/form-data'}
        }
        vm.$refs.cropper.getCropBlob(data => {
          let fd = new FormData()
          // 构造新File对象
          Object.defineProperties(vm.oldFile, {
            size: {
              value: data.size,
              writable: true
            },
            type: {
              value: data.type,
              writable: true
            }
          })
          fd.append('file', vm.oldFile)
          let url = Api.fileUpload.replace('{bucketName}', 'img')
          vm.$axios.post(url, fd, config).then(res => {
            if (res.code === 20000) {
              setTimeout(() => {
                vm.isLoading = false
                vm.myUrl = res.data.path
                vm.$message.success(res.msg)
              }, 1000)
            } else {
              vm.isLoading = false
              vm.$message.error(res.msg)
            }
          }).catch(err => {
            vm.$message.error(err.data.msg)
            vm.isLoading = false
          })
        })
      },
      // 实时预览函数
      realTime(data) {
        let previews = data
        let h = 0.5
        this.previewStyle = {
          width: previews.w + 'px',
          height: previews.h + 'px',
          overflow: 'hidden',
          margin: '0',
          zoom: h
        }
        this.previews = data
      },
      uploadImg(e) {
        // 上传图片
        const vm = this
        vm.$children[0].$refs.cropperImg.style.display = 'block'
        let file = e.target.files[0]
        vm.fileName = file.name || ''
        vm.oldFile = {}
        vm.oldFile = file
        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(e.target.value)) {
          vm.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种')
          return false
        }
        let isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          vm.$message.error('上传图片大小不能超过 2MB!')
          return false
        }
        let reader = new FileReader()
        reader.onload = e => {
          let data
          if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
          this.option.img = data
        }
        // 转化为blob
        reader.readAsArrayBuffer(file)
      },
      cropMoving(data) {
        this.option.cropData = data
      },
      clearCrop() {
        const vm = this
        vm.$refs.cropper.clearCrop()
        vm.$refs.referenceUpload.value = null
        vm.option.img = ''
        vm.fileName = ''
        vm.oldFile = {}
        vm.$refs.cropper.refresh()
        vm.$children[0].$refs.cropperImg.style.display = 'none'
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  @import "~/common.scss";

  .vue-cropper {
    width: 100%;
    height: 100%;
    .cropper-block {
      width: 100%;
      height: 400px;
    }
    .btn-block {
      padding: 10px 0;
      text-align: left;
      .handel-btn {
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        text-align: center;
        box-sizing: border-box;
        outline: none;
        padding: 9px 15px;
        margin-right: 10px;
        font-size: 14px;
        border-radius: 4px;
        color: $white;
        background-color: $blue;
        border-color: $blue;
        transition: all 0.2s ease;
        text-decoration: none;
        user-select: none;
      }
    }
    .pre-block {
      padding: 10px;
      border: 2px dashed $gray;
      overflow-y: hidden;
    }
    .upload-success {
      margin-top: 10px;
      padding: 10px 10px 20px 10px;
      border: 2px dashed $green;
      overflow: hidden;
      img {
        margin: 5px;
        width: 100%;
        height: 100%;
      }
    }
    .bk-green {
      background-color: $green !important;
      border-color: $green !important;
    }
  }
</style>
